var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var adminRouter = require('./routes/admin');
var articleRouter = require('./routes/article');
var commentsRouter = require('./routes/comments');
var imagesRouter = require('./routes/images');

// const session = require('express-session');
// const MongoStore = require('connect-mongo');
const { HOST, PORT, NAME } = require('./mongodb/config')
var app = express();

//允许跨域访问
app.use((req, res, next) => {
    res.set("Access-Control-Allow-Origin", "*"); // 或者指定的域名，如'http://127.0.0.1:5500'
    res.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 添加允许的方法
    if (req.method === 'OPTIONS') {
        // 预检请求直接返回200 OK
        return res.sendStatus(200);
    }
    next();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/public',express.static(path.join(__dirname, 'public')));

app.use('/', adminRouter);
app.use('/', articleRouter);
app.use('/', commentsRouter);
app.use('/', imagesRouter);

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   next(createError(404));
// });

// error handler
// app.use(function(err, req, res, next) {
//   // set locals, only providing error in development
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};

//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });

module.exports = app;
